<template>
  <div>
    <!-- 操作按钮 -->
    <el-row :gutter="20" class="gl_my_15">
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="openAddMember()">新增费用</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe size="mini">
      <el-table-column prop="name" label="费用名称">
        <template slot-scope="{row}">
          <div v-if="!row.isEdit">{{ row.name }}</div>
          <el-input v-else v-model.trim="row.nameInput" size="mini" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格">
        <template slot-scope="{row}">
          <div v-if="!row.isEdit">
            <span>￥</span>
            <span>{{ formatMoney(row.price) }}</span>
          </div>
          <el-input-number v-else v-model.trim="row.priceInput" :precision="2" :min="0" size="mini" :controls="false" @keyup.enter.native="clickComplete(row)" />
        </template>
      </el-table-column>
      <el-table-column prop="operating" label="操作" width="200">
        <template slot-scope="{row,$index}">
          <el-button v-if="!row.isEdit" size="mini" type="text" @click="clickEidt(row)">编辑</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickComplete(row)">完成</el-button>
          <el-button v-if="row.isEdit" size="mini" type="text" @click="clickCancel(row)">取消</el-button>
          <el-button v-if="!row.isEdit" type="text" size="mini" @click="deleteItem(row,$index)">
            <span class="gl_color_error">删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 子组件添加编辑 -->
    <test-form ref="testForm" :fee-type="'other'" @pushTabelData="getTabelDate" @editTabelData="updataTabelDate" />
  </div>
</template>

<script>
import testForm from './editFee';
import {
  api_GET_TrainTrainningFee, // 获取培训费用列表
  api_POST_TrainTrainningFee, // 新建培训费用
  api_PUT_TrainTrainningFeeId, // 更新培训费用
  api_DELETE_TrainTrainningFeeId, // 删除培训费用
  api_GET_TrainTrainningFeeId // 获取培训费用
} from '@/extend/api/trainswaggerApi/app.js';
import { Api_GET_TrainTrainningFeeQO } from '@/lib/form/train/swaggerForm.js';
export default {
  components: {
    testForm
  },
  data () {
    return {
      TrainningId: null,
      qo: new Api_GET_TrainTrainningFeeQO(),
      tableData: [],
      loading: false,
      totalPage: 0
    };
  },
  created() {
    this.init();
    this.getPageList();
  },
  methods: {
    // 初始化
    init() {
      this.TrainningId = this.$route.params.id;
    },
    // 获取数据
    getPageList() {
      this.qo.TrainningId = this.$route.params.id;
      this.loading = true;
      // 手动转换0为null
      this.qo.MinPrice = null;
      this.qo.MaxPrice = null;
      api_GET_TrainTrainningFee(this.qo).then(
        res => {
          this.loading = false;
          if (res.items) {
            const _res = res.items || [];
            this.tableData = _res.map(item => {
              item.isEdit = false;
              item.nameInput = '';
              item.priceInput = '';
              return item;
            });
            console.log('table', this.tableData);
          }
        }
      )
        .catch(
          error => {
            this.loading = false;
            this.$message({
              message: `列表获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 修改会员收费名称
    updateFeeName() {},
    // 新增会员
    openAddMember() {
      this.$refs.testForm.open();
    },
    // 编辑
    clickEidt(row, index) {
      api_GET_TrainTrainningFeeId(row.id).then(
        res => {
          row.nameInput = res.name;
          row.priceInput = this.formatMoney(res.price);
        }
      ).catch(
        error => {
          this.$message({
            message: '获取信息失败' + error.error.message,
            type: 'error',
            showClose: true
          });
        }
      );
      row.isEdit = true;
    },
    // 删除
    deleteItem(row, index) {
      this.$confirm(`您确定要删除${row.name}信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            this.postDelete(row);
          }
        );
    },
    postDelete(row) {
      api_DELETE_TrainTrainningFeeId(row.id).then(
        res => {
          this.$message({
            message: `删除成功`,
            type: 'success',
            showClose: true
          });
          this.getPageList();
        }
      ).catch(
        error => {
          this.$message({
            message: '删除失败' + error.error.message,
            type: 'error',
            showClose: true
          });
        }
      );
    },
    // 添加新信息
    getTabelDate(data) {
      data.trainningId = this.TrainningId;
      api_POST_TrainTrainningFee(data).then(
        res => {
          this.$message({
            message: '添加成功',
            type: 'success',
            showClose: true
          });
          this.getPageList();
        }
      ).catch(
        error => {
          this.$message({
            message: '添加失败' + error.error.message,
            type: 'error',
            showClose: true
          });
        }
      );
      this.$refs.testForm.close();
    },
    // 修改信息
    updataTabelDate(data) {
      this.$refs.testForm.close();
    },
    // 点击完成
    clickComplete (row) {
      const _vo = {
        trainningId: row.trainningId,
        name: row.nameInput,
        price: this.yuanToFen(row.priceInput)
      };
      api_PUT_TrainTrainningFeeId(row.id, _vo).then(
        res => {
          this.$message({
            message: `更新成功`,
            type: 'success',
            showClose: true
          });
          this.getPageList();
          row.isEdit = false;
        }
      ).catch(
        error => {
          this.$message({
            message: `更新失败 ${error.error.message}`,
            type: 'error',
            showClose: true
          });
          row.isEdit = false;
        }
      );
    },
    // 点击取消
    clickCancel (row) {
      row.isEdit = false;
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 将元转化为分
    yuanToFen(moneyStr) {
      const _moneyStr = String(moneyStr);
      const yuan = Number(_moneyStr.split('.')[0]) || 0;
      const fen = Number(_moneyStr.split('.')[1]) || 0;
      return yuan * 100 + fen;
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
